package xyz.penghaonan.wificonnect.connect;

import xyz.penghaonan.wificonnect.message.IMsg;
import xyz.penghaonan.wificonnect.message.KeepAliveRequestMsg;
import xyz.penghaonan.wificonnect.message.MsgReceiver;
import xyz.penghaonan.wificonnect.message.MsgSender;
import xyz.penghaonan.wificonnect.sockethelper.BaseSocketHelper;
import xyz.penghaonan.wificonnect.sockethelper.ClientSocketHelper;

public class PhoneConnectHelper extends BaseConnectHelper {
    private ClientSocketHelper socketHelper;

    private final Runnable keepAliveTask = new Runnable() {
        @Override
        public void run() {
            setState(STATE_OFF);
        }
    };

    @Override
    public BaseSocketHelper getSocketHelper() {
        return socketHelper;
    }

    public void connect(String ip) {
        releaseSocket();
        setState(STATE_SOCKET_CREATE);
        socketHelper = new ClientSocketHelper();
        socketHelper.postConnectToServer(ip);
        socketHelper.addReceiveListener(new MsgReceiver() {
            @Override
            protected void onMsgReceived(IMsg msg) {
                if (msg instanceof KeepAliveRequestMsg) {
                    setState(STATE_SOCKET_CONNECTED);
                    MsgSender.sendMsg(((KeepAliveRequestMsg) msg).createResponseMsg());
                    resetKeepAliveTimer();
                }
            }
        });
        setState(STATE_SOCKET_CONNECTING);
    }

    public void disconnect() {
        releaseSocket();
        setState(STATE_OFF);
    }

    private void resetKeepAliveTimer() {
        handler.removeCallbacks(keepAliveTask);
        handler.postDelayed(keepAliveTask, TIME_OUT);
    }

    private void releaseSocket() {
        if (socketHelper != null) {
            socketHelper.release();
            socketHelper = null;
        }
    }
}
